package main

import (
	"net/http"
	"Go-Exercise/immoc/errhandling/filelistingserver/filelisting"
	"os"
	"log"
)

/**
 * @description 
 * @time 2018/5/6 23:22
 * @version 
 */
func main() {

	http.HandleFunc("/list/",
		errWrapper(filelisting.HandleFileList))

	responseError := http.ListenAndServe(":8888", nil)
	if responseError != nil {
		panic(responseError)
	}
}

type appHandler func(writer http.ResponseWriter, request *http.Request) error

//handler是定义接收函数的类型
func errWrapper(handler appHandler) func(w http.ResponseWriter, r *http.Request) {
	return func(writer http.ResponseWriter, request *http.Request) {

		defer func() {

			if r := recover(); r != nil {
				log.Printf("Panic: %v", r)
				http.Error(writer, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			}
		}()

		err := handler(writer, request)
		if err != nil {
			log.Printf("error handling request: %s", err.Error())

			if userErr ,ok := err.(UserError); ok {
				http.Error(writer,userErr.Message(),http.StatusBadRequest)
				return
			}

			code := http.StatusOK
			switch {
			case os.IsNotExist(err):
				code = http.StatusNotFound
			case os.IsPermission(err):
				code = http.StatusForbidden
			default:
				code = http.StatusInternalServerError
			}
			http.Error(writer, http.StatusText(code), code)
		}
	}
}

type UserError interface {
	error
	Message() string
}
